/**
 * Created by sam on 16-11-21.
 */

var cheerio = require('cheerio');
var dao = require('./dao');
var utils = require('./utils');
var cookie = require('./cookie');
var common = require('../conf/common');

function loadDetail(asin,ep,num) {
    //var s = new Date().getTime();
    var source = common.getSource();
    var url = common.getDpUrl()+asin;
    utils.getc(url,num,function (html) {

        if(html === 'timeout'){
             ep.emit("sleep", asin);
        }else{
            var $ = cheerio.load(html);
            console.log(html)
            if($(".a-last").text().indexOf('robot')>0){
                console.log("Thread["+num+"] .... robot ....");
                //cookie.refresh();
                ep.emit("sleep", asin);
            }else{
                var pro_name = $("#productTitle").text().trim();
                if(pro_name=='' || isNaN(pro_name)){
                    pro_name = $("#btAsinTitle > span").text().trim();
                }
                var brand = $("#brand").text().trim();
                if(brand=='' || isNaN(brand)){
                    brand = $("#handleBuy > div:nth-child(18) > span > a").text().trim();
                }
                var cArr = $("#wayfinding-breadcrumbs_feature_div").text().split('›');
                var category ='';
                for(var i in cArr){
                    if(i==0){
                        category += cArr[i].trim();
                    }else {
                        category += "_"+ cArr[i].trim();
                    }
                }
                var sell_url = "";
                //自家的才记录asin
                if(brand=='ESR'){
                    $("li", $("#twister")).each(function () {
                        var bound_color = $(this).attr("data-defaultasin");
                        var bound_asin = $(this).attr("title").replace("Click to select ","");
                        var bound = {
                            asin:asin,
                            source:source,
                            bound_color:bound_color,
                            bound_asin:bound_asin
                        };
                        dao.saveBeBound(bound);
                    });
                    sell_url = $("#olp_feature_div a").attr("href");
                }


                //console.log("-->pro_name:"+pro_name+",brand:"+brand);
                //console.log("category:"+category);


                //ABSR
                var $details = $("#productDetails_detailBullets_sections1");
                var absr ='Best Sellers Rank:'; //
                $("tr>th",$details).each(function () {
                    var txt = $(this).text().trim();
                    if(txt=='Best Sellers Rank'){
                        var arr = $(this).next().text().split('#');
                        for(var i in arr){
                            if(arr[i].trim()!=''){
                                absr += "#"+ arr[i].trim()+"<br/>";
                            }
                        }
                        $(this).next().find("span>span").each(function () {
                            var cp = "";
                            var absr_url = "";
                            var len = $("a",$(this)).length-1;
                            var absr_rank = parseInt($(this).text().replace(",","").replace("#",""));
                            $("a",$(this)).each(function (i) {
                                if(i==len){
                                    absr_url = $(this).attr('href');
                                    cp += $(this).text();
                                }else{
                                    cp += $(this).text()+"_";
                                }
                            });
                            var ab_data = {
                                source:source,
                                asin:asin,
                                absr_rank:absr_rank,
                                absr_url:common.getDomain()+absr_url,
                                category_path:cp.replace("See Top 100 in ",""),
                            };
                            //console.log(ab_data);
                            dao.saveAbsrInfo(ab_data);
                        })
                    }
                });
                if($details==null || $details.length==0){
                    absr = $("#SalesRank").text().replace(/\s+/g, "").replace(/\..*}/g, "").replace(/#/g,"<br/>#").replace(/in/g," in ");
                }
                

                //console.log("absr:"+absr);
                //acrCustomerReviewLink
                var comm = parseInt($("#acrCustomerReviewText",$details).text().replace(",",""));
                if(comm || comm.length==0 || isNaN(comm)){
                    comm = $("#acrCustomerReviewText").text().replace(/\D+/g,"");
                }
                if(comm || comm.length==0 || isNaN(comm)){
                    comm = $("#handleBuy > span > span > a").text().replace(/\D+/g,"");
                }
                var grade = $("#avgRating span > a > span").text().trim().replace(" out of 5 stars","");
                if(grade==null || grade.length==0){
                    grade = $("#reviewStarsLinkedCustomerReviews > i > span").text().trim().replace(" out of 5 stars","");
                }
                if(grade==null || grade.length==0){
                    grade = $("#avgRating > span").text().trim().replace(" out of 5 stars","");
                }
                if(grade==null || grade.length==0){
                    grade = $("#acr-dpReviewsSummary-"+asin+" > div.gry.txtnormal.acrRating").text().trim().replace(" out of 5 stars","");
                }

                var price = $("#priceblock_ourprice").text();//priceblock_saleprice
                var is_sale = 0;
                if(price == ''){
                    price = $("#priceblock_saleprice").text();
                    is_sale = 1;
                }
                if(price == '') {
                    price = $("#actualPriceValue > b").text();
                    is_sale = 1;
                }

                //console.log("comm:"+comm,"avg:"+grade+",price:"+price);

                var star_5 = $(".a-nowrap > a",$("#histogramTable")).eq(1).text();
                if(star_5 ==''){
                    star_5 = $("div.fl.histoRowfive.clearboth > a > div.histoCount.fl.gl10.ltgry.txtnormal",$("#revH")).text();
                }
                var star_4 = $(".a-nowrap > a",$("#histogramTable")).eq(3).text();
                if(star_4 ==''){
                    star_4 = $("div.fl.histoRowfour.clearboth > a > div.histoCount.fl.gl10.ltgry.txtnormal",$("#revH")).text();
                }
                var star_3 = $(".a-nowrap > a",$("#histogramTable")).eq(5).text();
                if(star_3 == ''){
                    star_3 = $("div.fl.histoRowthree.clearboth > a > div.histoCount.fl.gl10.ltgry.txtnormal",$("#revH")).text();
                }
                var star_2 = $(".a-nowrap > a",$("#histogramTable")).eq(7).text();
                if(star_2 == ''){
                    star_2 = $("div.fl.histoRowtwo.clearboth > a > div.histoCount.fl.gl10.ltgry.txtnormal",$("#revH")).text();
                }
                var star_1 = $(".a-nowrap > a",$("#histogramTable")).eq(9).text();
                if(star_1 == ''){
                    star_1 = $("div.fl.histoRowone.clearboth > a > div.histoCount.fl.gl10.ltgry.txtnormal",$("#revH")).text();
                }

                //console.log("5:"+star_5+",4:"+star_4+",3:"+star_3+",2:"+star_2+",1:"+star_1);

                var imgs = $("#altImages");
                if(imgs=='' || isNaN(imgs)){
                    imgs = $("#thumbs-image");
                }
                $("img",imgs).each(function () {
                    var img = $(this).attr("src");
                    if (img.indexOf("play-button") == -1){
                        imgs += img.replace("_SX38_SY50_CR,0,0,38,50_.jpg","_SY300_QL70_.jpg")+";";
                    }
                });

               // console.log(imgs);
                var desc = '';
                $("#feature-bullets span").each(function () {
                    desc += $(this).text().trim()+";"
                });

                //console.log(desc);

                var parentAsin = $("#amsDetailRight").attr("data-detailpageasin");


                //console.log("parentAsin:"+parentAsin+",sell_url:"+sell_url);

                //Most helpful 评论
                $("#revMHRL>div").each(function () {
                    var reviewId = $(this).attr("id").replace("rev-dpReviewsMostHelpfulAUI-","");
                    var comm_url = $("div.a-row.a-spacing-micro > div > a:nth-child(1)",$(this)).attr("href");
                    if(comm_url == '' || isNaN(comm_url)){
                        comm_url = $("div.mt4.ttl > a",$(this)).attr("href");
                    }
                    var comm_grade = $("div.a-row.a-spacing-micro > div > a:nth-child(1) > i > span",$(this)).text().replace(" out of 5 stars","");
                    if(comm_grade == ''){
                        comm_grade = $("div.mt4.ttl > span.swSprite.s_star_5_0 > span",$(this)).text().replace(" out of 5 stars","");
                    }
                    var comm_title = $("div.a-row.a-spacing-micro > div > a:nth-child(3) > span",$(this)).text();
                    if(comm_title == ''){
                        comm_title = $("div.mt4.ttl > a > strong",$(this)).text();
                    }
                    var comm_name = $("div.a-row.a-spacing-micro > span > span.a-size-normal > a",$(this)).text();
                    var cust_url = $("div.a-row.a-spacing-micro > span > span.a-size-normal > a",$(this)).attr("href");
                    if(comm_name == ''){
                        comm_name = $("div.mt4.ath > span > span > a",$(this)).text();
                        cust_url = $("div.mt4.ath > span > span > a",$(this)).attr("href");
                    }
                    var comm_date = $("div.a-row.a-spacing-micro > span > span.a-color-secondary",$(this)).text();
                    if(comm_date == ''){
                        comm_date = $("div.mt4.ttl > span.gry.valignMiddle > span",$(this)).text();
                    }
                    var comm_color = $("#revData-dpReviewsMostHelpfulAUI-"+reviewId+" > span.a-size-mini.a-color-secondary").text();
                    if(comm_color == ''){
                        comm_color = $("div.txtsmall.mt4.fvavp > span:nth-child(2) > span.formatValue",$(this)).text();
                    }
                    var comment = $("#revData-dpReviewsMostHelpfulAUI-"+reviewId+" > div").text().trim();
                    if(comment == ''){
                        comment = $("div.mt9.reviewText > div",$(this)).text();
                    }
                    var comm_imgs = '';
                    $(".review-image-thumbnail",$(this)).each(function () {
                        comm_imgs += $(this).attr("src")+";";
                    });

                    var comm_create = common.formatDate(comm_date);

                    /*console.log("================================");
                    console.log("reviewId:"+reviewId+",createDate:"+comm_create+",grade:"+comm_grade+",title:"+comm_title);
                    console.log("name:"+comm_name+",date:"+comm_date+",color:"+comm_color+",cust_url:"+cust_url);
                    console.log("comm_url:"+comm_url);
                    console.log("comm_cent:"+comment);
                    console.log("comm_imgs:"+comm_imgs);
                    console.log("================================");
                    console.log("");*/

                    var dd = {
                        source:source,
                        reviewId:reviewId,
                        comm_url:comm_url,
                        comment:utils.replaceEmoji(comment),
                        comm_imgs:comm_imgs,
                        comm_grade:comm_grade,
                        comm_title:utils.replaceEmoji(comm_title),
                        comm_name:comm_name,
                        cust_url:common.getDomain()+cust_url,
                        comm_date:comm_date,
                        comm_create:comm_create,
                        comm_color:comm_color.replace("Color: ",""),
                        asin:asin,
                    };
                    dao.saveProMHRL(dd);

                });

                var data = {
                    source:source,
                    asin:asin,
                    pro_name:pro_name,
                    brand:brand,
                    category:category,
                    absr:absr,
                    imgs:imgs,
                    desc:desc,
                    comm:comm,
                    grade:grade,
                    price:price,
                    parentAsin:parentAsin,
                    sell_url:sell_url,
                    is_sale:is_sale,
                    star_1:star_1,
                    star_2:star_2,
                    star_3:star_3,
                    star_4:star_4,
                    star_5:star_5,
                };

                dao.savePro(data);
                console.log(data);
                ep.emit('next_asin', asin);
                //var e = new Date().getTime();
                //console.log("Thread["+num+"] open time:"+(e-s))
            }
        }
    })
}

module.exports.loadDetail = loadDetail;
/*function test() {
console.log(123)
    //cookie.refresh(1,function () {
        loadDetail('B00EG0C3S2','',1);
        //loadDetail('B00B7U6O2A');
    //});
}

test();*/





